//
//  NetworkTool.m
//  WWTQ
//
//  Created by JP on 2018/10/26.
//  Copyright © 2018年 Jqert. All rights reserved.
//

#import "NetworkTool.h"
#import "AFNetworkActivityIndicatorManager.h"

@implementation NetworkTool

static AFHTTPSessionManager *_manager;

+ (AFHTTPSessionManager *)sharedMangager {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _manager = [AFHTTPSessionManager manager];
        _manager.requestSerializer.timeoutInterval = 10.0f;
        
//        _manager.requestSerializer = [AFJSONRequestSerializer serializer];
        //        //响应格式
        _manager.responseSerializer = [AFJSONResponseSerializer serializer];
//        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html", nil];
        _manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html", @"text/xml", @"text/plain", nil];
        [AFNetworkActivityIndicatorManager sharedManager].enabled = YES;
        
    });
    return _manager;
}

+ (void)requestWeatherMessage:(NSString *)cityID successBlock:(SuccBlock)successBlock failureBlock:(FailBlock)failureBlock {
    if (![[self getInternetStatus] isEqualToString:@"notReachable"]) {
        NSString *urlStr = [NSString stringWithFormat:@"http://t.weather.sojson.com/api/weather/city/%@", cityID];
        [[self sharedMangager] GET:urlStr parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            successBlock(responseObject);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSString *errorStr = [error.userInfo objectForKey:@"NSLocalizedDescription"];
            failureBlock(errorStr);
        }];
    } else {
        buildErrorSVP(NoErrorForDeleCartItem);
    }
}


#pragma mark - 获取网络状态
+ (NSString *)getInternetStatus {
    Reachability *reachability  = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    NSString *net = @"wifi";
    switch (internetStatus) {
        case ReachableViaWiFi:
            net = @"wifi";
            break;
        case ReachableVia2G:
            net = @"2G";
            break;
        case ReachableVia3G:
            net = @"3G";
            break;
        case ReachableVia4G:
            net = @"4G";
            break;
            
        case NotReachable:
            net = @"notReachable";
        default:
            break;
    }
    return net;
}

@end
